package com.itheima.service.impl;


import com.itheima.common.entity.QueryPageBean;
import com.itheima.common.utils.DateUtils;
import com.itheima.mapper.MemberDao;
import com.itheima.mapper.OrderDao;
import com.itheima.mapper.OrderSettingDao;
import com.itheima.pojo.*;
import com.itheima.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OrderServiceimpl implements OrderService {

    @Autowired
    OrderDao orderDao;
    @Autowired
    OrderSettingDao orderSettingDao;
    @Autowired
    MemberDao memberDao;
    @Override
    public Long findCount() {

        return orderDao.findCount();


    }

    @Override
    public List<OrderVO> findPage(QueryPageBean queryPageBean) {

        int start = (queryPageBean.getCurrentPage() - 1) * queryPageBean.getPageSize();
        int end = start + queryPageBean.getPageSize();
        List<OrderVO> orderVOS = orderDao.findPage(start, end, queryPageBean.getQueryString());
        return orderVOS;

    }

    @Override
    public void update(Order order) {

        orderDao.update(order);


    }

    @Override
    public OrderVO2 findById(Integer id) {

        OrderVO2 orderVO2 = orderDao.findById(id);
        return orderVO2;

    }



    @Override
    public Integer add(OrderTOD orderTOD) {



//          判断是否是会员
        Long memberId = memberDao.findMemberIdByIdCard(orderTOD.getName(),orderTOD.getTelephone());
        if (memberId == null){
            throw new RuntimeException("不是会员");
        }
//        判断预约日期的预约人数是否设置

            OrderSetting orderSetting = orderSettingDao.findByOrderDate(orderTOD.getOrderDate());

            if (orderSetting == null) {
                throw new RuntimeException("预约日期没有预约设置");
            }
//            判断预约人数是否已满
            if (orderSetting.getReservations() >= orderSetting.getNumber()) {
                throw new RuntimeException("预约人数已满");
            }
//            判断是否重复预约
            Long OrderId = orderDao.findByNameAndOrderDateAndSetmeal(orderTOD);
            if (OrderId != null) {
                throw new RuntimeException("该用户已经预约过了");
            }

        Order order = null;
        try {
            order = new Order(memberId.intValue(), DateUtils.parseString2Date(orderTOD.getOrderDate(), "yyyy-MM-dd"),  Order.ORDERTYPE_WEIXIN, Order.ORDERSTATUS_NO,orderTOD.getSetmealId().intValue());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        orderDao.add(order);


//        更新人数
        orderSetting.setReservations(orderSetting.getReservations() + 1);
        orderSettingDao.editReservations(orderSetting);
        return order.getId();

    }
}
